package com.rephilo.proxy;

import com.rephilo.annotation.Transactional;
import com.rephilo.factory.BeanFactory;
import com.rephilo.utils.TransactionManager;

import java.lang.reflect.Method;

/**
 * @author rephilo
 */
public class ProxyTransaction {
    /**
     * 执行代理类中的Transaction操作
     *
     * @param proxy
     * @param method
     * @param args
     */
    public Object doMethodInvokeWithTransaction(Object proxy, Method method, Object[] args) throws Exception {
        Object result;
        Method implMethod = proxy.getClass().getMethod(method.getName(), method.getParameterTypes());
        if (method.getAnnotation(Transactional.class) != null || implMethod.getAnnotation(Transactional.class) != null) {
            TransactionManager transactionManager = (TransactionManager) BeanFactory.getBean("transactionManager");
            try {
                // 开启事务(关闭事务的自动提交)
                transactionManager.beginTransaction();
                result = method.invoke(proxy, args);
                // 提交事务
                transactionManager.commit();
            } catch (Exception e) {
                e.printStackTrace();
                // 回滚事务
                transactionManager.rollback();
                // 抛出异常
                throw e;
            }
        } else {
            result = method.invoke(proxy, args);
        }

        return result;
    }
}
